package com.mall.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;

/**
 * @program: cs-mall
 * @description:
 * @author: 热心市民小刘
 * @create: 2021-04-26 16:47
 **/
@Component
@Slf4j
public class DelayCancelOrderProducer {
    private DefaultMQProducer producer;

    public static final String DELAY_ORDER_TOPIC = "delay_order_topic";

    @PostConstruct
    public void init() {


        producer = new DefaultMQProducer("delay_cancel_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            log.error("消息生产者启动失败···");
        }
    }

    //发送延时消息的方法
    public void sendDelayCannelMessage(String orderId) {
        SendResult send = null;

        try {
            Message message = new Message();
            message.setTopic(DELAY_ORDER_TOPIC);
            message.setBody(orderId.getBytes("utf-8"));
            //delay级别，修改延时级别
            message.setDelayTimeLevel(16);


            send = producer.send(message);



        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        }

        if (send.getSendStatus().equals(SendStatus.SEND_OK)) {
            log.info("消息发送成功，消息的id为{}", send.getMsgId());

        }


    }


}
